package com.example.databackup.controller;

import com.example.databackup.Util.*;
import com.jcraft.jsch.*;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RequestMapping("/backups")
@RestController
public class backupsController {
    private String username = "root";
    private String password = "root123456";

    @GetMapping("/backupRecover")
    @ResponseBody
    public MessageUtil backupRecover(HttpServletResponse response, HostUtil hostUtil) {
        MessageUtil messageUtil = new MessageUtil();
        String backupFile = "/home/backups/back.sql";
        try {

            JSch jsch = new JSch();
            Session session = jsch.getSession(username, hostUtil.getHost().toString(), hostUtil.getPort());
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            String command = " mysqldump -u root -proot yf_device_sys >" + backupFile;
            ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
            //执行命令行命令
            channelExec.setCommand(command);
            channelExec.connect(3000);
            //创建输入流
            BufferedReader reader = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
            String line;
            try {
                while ((line = reader.readLine()) != null) {

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            channelExec.disconnect();
            //将备份文件保存到本地
            ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect(3000);
            FileOutputStream fileOutputStream = new FileOutputStream(String.valueOf(reader));
            channelSftp.get(backupFile, fileOutputStream);
            session.disconnect();

            try {
                String filename = "public.sql";
                // 以流的形式下载文件。
                InputStream fis = new BufferedInputStream(new FileInputStream(String.valueOf(reader)));
                channelSftp.setOutputStream(System.out);
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();
                response.setContentType("application/json;charset=utf-8");
                String fileName = new String(filename.getBytes("gb2312"), "iso8859-1");
                response.setHeader("Content-disposition", "attachment;filename=" + fileName);
                OutputStream outputStream = response.getOutputStream();
                outputStream.write(buffer);
                outputStream.flush();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
                messageUtil.setMessage("文件下载出现异常" + e);
                messageUtil.setCode(201);
            }
            channelSftp.disconnect();

        } catch (IOException | JSchException e) {
            e.printStackTrace();
            messageUtil.setMessage("服务器状态异常连接失败");
            messageUtil.setCode(0);
        } catch (SftpException e) {
            throw new RuntimeException(e);
        }
        messageUtil.setMessage("数据库备份成功");
        messageUtil.setCode(200);
        return messageUtil;
    }

    //上传文件
    @ResponseBody
    @RequestMapping(value = "/fileUpload")
    public MessageUtil upload(HostUtil hostUtil) throws Exception {
        Session session = null;
        Channel channel = null;
        MessageUtil messageUtil = new MessageUtil();
        //连接sftp工具类
        //获取原始文件名
        File mkFile = new File("D:/uploadFile");
        if (!mkFile.exists() && !mkFile.isDirectory()) {
            mkFile.mkdirs();
        }
        //输出文件流
        InputStream in = hostUtil.getFile().getInputStream();

        //创建文件
        String dir = "/home/backups/";
        String name = "public.sql";
        ChannelSftp channelSftp = null;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(username, hostUtil.getHost(), hostUtil.getPort());
            session.setPassword(password);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp) channel;
            channelSftp.put(in, dir + name, ChannelSftp.OVERWRITE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        channelSftp.exit();
        channel.disconnect();
        session.disconnect();
        //文件上传服务器
        messageUtil.setMessage("上传文件成功");
        messageUtil.setCode(200);
        in.close();
        return messageUtil;
    }

    //恢复数据
    @PostMapping("/recoveryData")
    public MessageUtil recoveryData(HostUtil hostUtil) {
        MessageUtil messageUtil = new MessageUtil();
        try {

            JSch jsch = new JSch();
            Session session = jsch.getSession(username, hostUtil.getHost(), hostUtil.getPort());
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            System.out.print(session);

            Channel channel = session.openChannel("shell");

            channel.setInputStream(new ByteArrayInputStream("mysql -uroot -proot --default-character-set=utf8 yf_device_sys  < /home/backups/public.sql\n".getBytes()));
            channel.setOutputStream(System.out);
            channel.connect(3 * 1000);
            messageUtil.setMessage("更新数据成功");
            messageUtil.setCode(200);
        } catch (JSchException e) {
            e.printStackTrace();
            messageUtil.setMessage("服务器状态异常连接失败");
            messageUtil.setCode(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return messageUtil;
    }
}
